{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Convolutions for Images\n",
    "\n",
    ":label:`sec_conv_layer`\n",
    "\n",
    "\n",
    "Now that we understand how convolutional layers work in theory,\n",
    "we are ready to see how they work in practice.\n",
    "Building on our motivation of convolutional neural networks\n",
    "as efficient architectures for exploring structure in image data,\n",
    "we stick with images as our running example.\n",
    "\n",
    "\n",
    "## The Cross-Correlation Operator\n",
    "\n",
    "Recall that strictly speaking, *convolutional* layers \n",
    "are a (slight) misnomer, since the operations they express\n",
    "are more accurately described as cross correlations.\n",
    "In a convolutional layer, an input array\n",
    "and a *correlation kernel* array are combined\n",
    "to produce an output array through a cross-correlation operation.\n",
    "Let's ignore channels for now and see how this works \n",
    "with two-dimensional data and hidden representations.\n",
    "In :numref:`fig_correlation`, \n",
    "the input is a two-dimensional array\n",
    "with a height of 3 and width of 3.\n",
    "We mark the shape of the array as $3 \\times 3$ or ($3$, $3$).\n",
    "The height and width of the kernel are both $2$.\n",
    "Note that in the deep learning research community,\n",
    "this object may be referred to as *a convolutional kernel*, \n",
    "*a filter*, or simply the layer's *weights*.\n",
    "The shape of the kernel window\n",
    "is given by the height and width of the kernel\n",
    "(here it is $2 \\times 2$).\n",
    "\n",
    "![Two-dimensional cross-correlation operation. The shaded portions are the first output element and the input and kernel array elements used in its computation: $0\\times0+1\\times1+3\\times2+4\\times3=19$. ](https://raw.githubusercontent.com/d2l-ai/d2l-en/master/img/correlation.svg)\n",
    "\n",
    ":label:`fig_correlation`\n",
    "\n",
    "\n",
    "In the two-dimensional cross-correlation operation,\n",
    "we begin with the convolution window positioned\n",
    "at the top-left corner of the input array\n",
    "and slide it across the input array,\n",
    "both from left to right and top to bottom.\n",
    "When the convolution window slides to a certain position,\n",
    "the input subarray contained in that window\n",
    "and the kernel array are multiplied (elementwise)\n",
    "and the resulting array is summed up\n",
    "yielding a single scalar value.\n",
    "This result gives the value of the output array\n",
    "at the corresponding location.\n",
    "Here, the output array has a height of 2 and width of 2\n",
    "and the four elements are derived from\n",
    "the two-dimensional cross-correlation operation:\n",
    "\n",
    "$$\n",
    "0\\times0+1\\times1+3\\times2+4\\times3=19,\\\\\n",
    "1\\times0+2\\times1+4\\times2+5\\times3=25,\\\\\n",
    "3\\times0+4\\times1+6\\times2+7\\times3=37,\\\\\n",
    "4\\times0+5\\times1+7\\times2+8\\times3=43.\n",
    "$$\n",
    "\n",
    "Note that along each axis, the output \n",
    "is slightly *smaller* than the input.\n",
    "Because the kernel has width and height greater than one,\n",
    "we can only properly compute the cross-correlation\n",
    "for locations where the kernel fits wholly within the image,\n",
    "the output size is given by the input size $H \\times W$\n",
    "minus the size of the convolutional kernel $h \\times w$\n",
    "via $(H-h+1) \\times (W-w+1)$.\n",
    "This is the case since we need enough space\n",
    "to 'shift' the convolutional kernel across the image\n",
    "(later we will see how to keep the size unchanged\n",
    "by padding the image with zeros around its boundary\n",
    "such that there is enough space to shift the kernel).\n",
    "Next, we implement this process in the `corr2d` function,\n",
    "which accepts the input array `X` and kernel array `K`\n",
    "and returns the output array `Y`.\n",
    "\n",
    "But first we will import the relevant libraries."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load ../utils/djl-imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public NDArray corr2d(NDArray X, NDArray K){\n",
    "    // Compute 2D cross-correlation.\n",
    "    int h = (int) K.getShape().get(0);\n",
    "    int w = (int) K.getShape().get(1);\n",
    "\n",
    "    NDArray Y = manager.zeros(new Shape(X.getShape().get(0) - h + 1, X.getShape().get(1) - w + 1));\n",
    "\n",
    "    for(int i=0; i < Y.getShape().get(0); i++){\n",
    "        for(int j=0; j < Y.getShape().get(1); j++){\n",
    "            Y.set(new NDIndex(i + \",\" + j), X.get(i + \":\" + (i+h) + \",\" + j + \":\" + (j+w)).mul(K).sum());\n",
    "        }\n",
    "    }\n",
    "\n",
    "    return Y;\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can construct the input array `X` and the kernel array `K`\n",
    "from the figure above\n",
    "to validate the output of the above implementation\n",
    "of the two-dimensional cross-correlation operation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NDManager manager = NDManager.newBaseManager();\n",
    "NDArray X = manager.create(new float[]{0,1,2,3,4,5,6,7,8}, new Shape(3,3));\n",
    "NDArray K = manager.create(new float[]{0,1,2,3}, new Shape(2,2));\n",
    "System.out.println(corr2d(X, K));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Convolutional Layers\n",
    "\n",
    "A convolutional layer cross-correlates the input and kernels\n",
    "and adds a scalar bias to produce an output.\n",
    "The two parameters of the convolutional layer\n",
    "are the kernel and the scalar bias.\n",
    "When training models based on convolutional layers,\n",
    "we typically initialize the kernels randomly,\n",
    "just as we would with a fully connected layer.\n",
    "\n",
    "We are now ready to implement a two-dimensional convolutional layer\n",
    "based on the `corr2d` function defined above.\n",
    "In the `ConvolutionalLayer` constructor function,\n",
    "we declare `weight` and `bias` as the two class parameters.\n",
    "The forward computation function `forward`\n",
    "calls the `corr2d` function and adds the bias.\n",
    "As with $h \\times w$ cross-correlation\n",
    "we also refer to convolutional layers\n",
    "as $h \\times w$ convolutions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "70"
    }
   },
   "outputs": [],
   "source": [
    "public class ConvolutionalLayer{\n",
    "    \n",
    "    private NDArray w;\n",
    "    private NDArray b;\n",
    "    \n",
    "    public NDArray getW(){\n",
    "        return w;\n",
    "    }\n",
    "    \n",
    "    public NDArray getB(){\n",
    "        return b;\n",
    "    }\n",
    "    \n",
    "    public ConvolutionalLayer(Shape shape){\n",
    "        NDManager manager = NDManager.newBaseManager();\n",
    "        w = manager.create(shape);\n",
    "        b = manager.randomNormal(new Shape(1));\n",
    "        w.setRequiresGradient(true);\n",
    "    }\n",
    "    \n",
    "    public NDArray forward(NDArray X){\n",
    "        return corr2d(X, w).add(b);\n",
    "    }\n",
    "    \n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Object Edge Detection in Images\n",
    "\n",
    "Let's take a moment to parse a simple application of a convolutional layer:\n",
    "detecting the edge of an object in an image\n",
    "by finding the location of the pixel change.\n",
    "First, we construct an 'image' of $6\\times 8$ pixels.\n",
    "The middle four columns are black (0) and the rest are white (1)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "66"
    }
   },
   "outputs": [],
   "source": [
    "X = manager.ones(new Shape(6,8));\n",
    "X.set(new NDIndex(\":\" + \",\" + 2 + \":\" + 6), 0f);\n",
    "System.out.println(X);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we construct a kernel `K` with a height of $1$ and width of $2$.\n",
    "When we perform the cross-correlation operation with the input,\n",
    "if the horizontally adjacent elements are the same,\n",
    "the output is 0. Otherwise, the output is non-zero."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "67"
    }
   },
   "outputs": [],
   "source": [
    "K = manager.create(new float[]{1, -1}, new Shape(1,2));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We are ready to perform the cross-correlation operation\n",
    "with arguments `X` (our input) and `K` (our kernel).\n",
    "As you can see, we detect 1 for the edge from white to black\n",
    "and -1 for the edge from black to white.\n",
    "All other outputs take value $0$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "69"
    }
   },
   "outputs": [],
   "source": [
    "NDArray Y = corr2d(X, K);\n",
    "Y"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can now apply the kernel to the transposed image.\n",
    "As expected, it vanishes. The kernel `K` only detects vertical edges."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "corr2d(X.transpose(), K);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Learning a Kernel\n",
    "\n",
    "Designing an edge detector by finite differences `[1, -1]` is neat\n",
    "if we know this is precisely what we are looking for.\n",
    "However, as we look at larger kernels,\n",
    "and consider successive layers of convolutions,\n",
    "it might be impossible to specify\n",
    "precisely what each filter should be doing manually.\n",
    "\n",
    "Now let us see whether we can learn the kernel that generated `Y` from `X`\n",
    "by looking at the (input, output) pairs only.\n",
    "We first construct a convolutional layer\n",
    "and initialize its kernel as a random array.\n",
    "Next, in each iteration, we will use the squared error\n",
    "to compare `Y` to the output of the convolutional layer.\n",
    "We can then calculate the gradient to update the weight.\n",
    "For the sake of simplicity, in this convolutional layer,\n",
    "we will ignore the bias.\n",
    "\n",
    "This time, we will use the in-built `Block` and `Conv2d` class from DJL. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X = X.reshape(1,1,6,8);\n",
    "Y = Y.reshape(1,1,6,7);\n",
    "\n",
    "Loss l2Loss = Loss.l2Loss();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "83"
    }
   },
   "outputs": [],
   "source": [
    "// Construct a two-dimensional convolutional layer with 1 output channel and a\n",
    "// kernel of shape (1, 2). For the sake of simplicity, we ignore the bias here\n",
    "Block block = Conv2d.builder()\n",
    "                .setKernelShape(new Shape(1, 2))\n",
    "                .optBias(false)\n",
    "                .setFilters(1)\n",
    "                .build();\n",
    "\n",
    "block.setInitializer(new NormalInitializer(), Parameter.Type.WEIGHT);\n",
    "block.initialize(manager, DataType.FLOAT32, X.getShape());\n",
    "\n",
    "// The two-dimensional convolutional layer uses four-dimensional input and\n",
    "// output in the format of (example, channel, height, width), where the batch\n",
    "// size (number of examples in the batch) and the number of channels are both 1\n",
    "\n",
    "ParameterList params = block.getParameters();\n",
    "NDArray wParam = params.get(0).getValue().getArray();\n",
    "wParam.setRequiresGradient(true);\n",
    "\n",
    "NDArray lossVal = null;\n",
    "ParameterStore parameterStore = new ParameterStore(manager, false);\n",
    "\n",
    "NDArray lossVal = null;\n",
    "\n",
    "for (int i = 0; i < 10; i++) {\n",
    "\n",
    "    wParam.setRequiresGradient(true);\n",
    "\n",
    "    try (GradientCollector gc = Engine.getInstance().newGradientCollector()) {\n",
    "        NDArray yHat = block.forward(parameterStore, new NDList(X), true).singletonOrThrow();\n",
    "        NDArray l = l2Loss.evaluate(new NDList(Y), new NDList(yHat));\n",
    "        lossVal = l;\n",
    "        gc.backward(l);\n",
    "    }\n",
    "    // Update the kernel\n",
    "    wParam.subi(wParam.getGradient().mul(0.40f));\n",
    "    \n",
    "    if((i+1)%2 == 0){\n",
    "        System.out.println(\"batch \" + (i+1) + \" loss: \" + lossVal.sum().getFloat());\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the error has dropped to a small value after 10 iterations. Now we will take a look at the kernel array we learned."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ParameterList params = block.getParameters();\n",
    "NDArray wParam = params.get(0).getValue().getArray();\n",
    "wParam"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Indeed, the learned kernel array is moving close\n",
    "to the kernel array `K` we defined earlier.\n",
    "\n",
    "## Cross-Correlation and Convolution\n",
    "\n",
    "Recall our observation from the previous section of the correspondence \n",
    "between the cross-correlation and convolution operators.\n",
    "The figure above makes this correspondence apparent.\n",
    "Simply flip the kernel from the bottom left to the top right.\n",
    "In this case, the indexing in the sum is reverted,\n",
    "yet the same result can be obtained.\n",
    "In keeping with standard terminology with deep learning literature,\n",
    "we will continue to refer to the cross-correlation operation\n",
    "as a convolution even though, strictly-speaking, it is slightly different.\n",
    "\n",
    "## Summary\n",
    "\n",
    "* The core computation of a two-dimensional convolutional layer is a two-dimensional cross-correlation operation. In its simplest form, this performs a cross-correlation operation on the two-dimensional input data and the kernel, and then adds a bias.\n",
    "* We can design a kernel to detect edges in images.\n",
    "* We can learn the kernel's parameters from data.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Construct an image `X` with diagonal edges.\n",
    "    * What happens if you apply the kernel `K` to it?\n",
    "    * What happens if you transpose `X`?\n",
    "    * What happens if you transpose `K`?\n",
    "1. When you try to automatically find the gradient for the `Conv2d` class we created, what kind of error message do you see?\n",
    "1. How do you represent a cross-correlation operation as a matrix multiplication by changing the input and kernel arrays?\n",
    "1. Design some kernels manually.\n",
    "    * What is the form of a kernel for the second derivative?\n",
    "    * What is the kernel for the Laplace operator?\n",
    "    * What is the kernel for an integral?\n",
    "    * What is the minimum size of a kernel to obtain a derivative of degree $d$?\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
